package com.meida.module.bus.provider.api;

import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.util.TypeUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.annotation.LoginRequired;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.FlymeUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmMaterial;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmUnit;
import com.meida.module.bus.client.entity.srmapi.oa.ApprovalBackReq;
import com.meida.module.bus.client.entity.srmapi.oa.BusOaApprovalSync;
import com.meida.module.bus.client.entity.srmapi.psmtosrm.PMSResultBody;
import com.meida.module.bus.provider.api.service.PmsOaApiService;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.soap.SoapClient;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.service.srmservice.SrmSqlserCommonService;
import com.meida.module.bus.provider.service.srmservice.SrmUnitService;
import com.meida.module.bus.provider.service.srmservice.SynchroSrmToPmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import java.util.Map;


/**
 * 控制器
 *
 * @author ldc
 * @date 2020-09-26
 */
@Slf4j
@Api(tags = "PMS-OA回调接口服務")
@RestController
@RequestMapping("/OaApi")
public class PmsOaApi {
    @Autowired
    private SynchroSrmToPmsService synchroSrmToPmsService;
    @Autowired
    private SyncSrmService syncSrmService;
    @Autowired
    private BusPurchaseService busPurchaseService;
    @Autowired
    private BusPurchaseDetailsService busPurchaseDetailsService;
    @Autowired
    private BusMaterialPlan100Service busMaterialPlan100Service;
    @Autowired
    private BusMaterialPlan200Service busMaterialPlan200Service;
    @Autowired
    private BusMaterialPackage100Service busMaterialPackage100Service;
    @Autowired
    private BusMaterialPackage200Service busMaterialPackage200Service;
    @Autowired
    private BusProjectSupplierService busProjectSupplierService;
    @Autowired
    private PmsOaApiService pmsOaApiService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private PmsApiUtil pmsApiUtil;
    @Autowired
    private BusOaApprovalSyncService syncService;

    @Autowired
    private SrmSqlserCommonService srmSqlserCommonService;

    @Autowired
    private SrmUnitService srmUnitService;
    @Autowired
    private BusOaApprovalSyncService oaApprovalSyncService;

    @Autowired
    private BusMajorService busMajorService;
    @Autowired
    private BaseUserService userService;
    @Autowired
    private BusOaApprovalSyncDetailService syncOaDetailService;

    @RequestMapping(value = "/syncApproval", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @LoginRequired(required = false)
    public ResultBody syncApproval(Long projectId) {
        pmsOaApiService.syncApproval(projectId);
        return ResultBody.ok("同步完成！");
    }

    @ApiOperation(value = "通用审批回调接口")
    @RequestMapping(value = "/approvalBackReq", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @LoginRequired(required = false)
    public PMSResultBody approvalBackReq(@Valid @RequestBody ApprovalBackReq approvalBackReq) throws Exception {
        StaticLog.info("-------通用审批回调接口-------");
        StaticLog.info("approvalBackReq--requestId： " + approvalBackReq.getRequestId());
        StaticLog.info("approvalBackReq--OA原始返回--approvalStatus： " + approvalBackReq.getApprovalStatus());
        // approvalBackReq.getApprovalStatus() OA驳回是0
        // approvalBackReq.getApprovalStatus() OA同意是3
        if(ApiConstants.OA_BACK_REJECT == approvalBackReq.getApprovalStatus()) {
            approvalBackReq.setApprovalStatus(ApiConstants.APPROVAL_REJECT);
        } else if(ApiConstants.OA_BACK_SUCCESS == approvalBackReq.getApprovalStatus()) {
            approvalBackReq.setApprovalStatus(ApiConstants.APPROVAL_SUCCESS);
        }
        if(ApiConstants.APPROVAL_REJECT == approvalBackReq.getApprovalStatus()) {
            StaticLog.info("approvalBackReq--驳回消息测试打印-----------------------");
            StaticLog.info("approvalBackReq--驳回消息测试打印-----------------------");
        }
        if(ApiConstants.APPROVAL_SUCCESS == approvalBackReq.getApprovalStatus()) {
            StaticLog.info("approvalBackReq--同意消息测试打印-----------------------");
            StaticLog.info("approvalBackReq--同意消息测试打印-----------------------");
        }
        StaticLog.info("approvalBackReq--转换PMS返回--approvalStatus： " + approvalBackReq.getApprovalStatus());
        Map<String, Object> searchMap = Maps.newHashMap();
        searchMap.put(ApiConstants.MAP_REQUESTID, approvalBackReq.getRequestId());
        Collection<BusOaApprovalSync> oaApprovalSyncs = syncService.listByMap(searchMap);
        if (0 == oaApprovalSyncs.size()) {
            StaticLog.info("该requestId无流程:" + approvalBackReq.getRequestId());
            return PMSResultBody.ok("1");
        }
        BusOaApprovalSync busOaApprovalSync = oaApprovalSyncs.stream().findFirst().get();
        if(ApiConstants.ENGINEER_APPROVAL_WZ_REQ.equals(busOaApprovalSync.getFlowNum())) {
            StaticLog.info("-------材料申请物料修复-------start");
            Map applyMap = redisUtils.getMap(approvalBackReq.getRequestId());
            BusPurchase purchase = (BusPurchase) applyMap.get("purchase");
            purchase.getDetails().stream().forEach(detailObj->{
                Map<String, Object> materialMap = Maps.newHashMap();
                materialMap.put("materialCode", detailObj.getMaterialCode());
                StaticLog.info("---材料申请物料修复----materialCode--:" + detailObj.getMaterialCode());
                List<SrmMaterial> srmMaterialList = srmSqlserCommonService.getSrmMaterial(materialMap);
                if(0 < srmMaterialList.size()) {
                    StaticLog.info("---材料申请物料修复----materialCode-有数据-:" + detailObj.getMaterialCode());
                    detailObj.setUnitCode(srmMaterialList.get(0).getBaseUnitCode());
                    StaticLog.info("---材料申请物料修复----getBaseUnitCode-:" + srmMaterialList.get(0).getBaseUnitCode());
                    Map<String, Object> unitMap = Maps.newHashMap();
                    unitMap.put("UNITCODE", srmMaterialList.get(0).getBaseUnitCode());
                    if(0 < srmUnitService.listByMap(unitMap).size()) {
                        detailObj.setUnitName(srmUnitService.listByMap(unitMap).stream().findFirst().get().getUnitName());
                    }
                   StaticLog.info("---材料申请物料修复----setUnitName-:" + detailObj.getUnitName());
                }
//                SrmUnit srmUnit = pmsApiUtil.getSrmUnitByMaterialCode(detailObj.getMaterialCode());
//                detailObj.setUnitCode(srmUnit.getUnitCode());
//                detailObj.setUnitName(srmUnit.getUnitName());
            });
            applyMap.put("purchase", purchase);
            redisUtils.setMap(approvalBackReq.getRequestId(), applyMap);
            StaticLog.info("-------材料申请物料修复----保存到redis---getRequestId:" + approvalBackReq.getRequestId());
            StaticLog.info("-------材料申请物料修复----保存到redis---applyMap:" + applyMap);
            StaticLog.info("-------材料申请物料修复-------end");
        }

        // 回调详细处理
        pmsOaApiService.oaApprovalBk(approvalBackReq);

        // 更新状态
        busOaApprovalSync.setStatus(String.valueOf(ApiConstants.APPROVAL_SUCCESS));
        StaticLog.info("-------更新OA审核状态-------start");
        Boolean updResult = syncService.updateById(busOaApprovalSync);
        StaticLog.info("-------更新OA审核状态-------updResult:" + updResult);
        StaticLog.info("-------更新OA审核状态-------end");
        return PMSResultBody.ok("0");
    }

    private void materialRequest() {
        BusPurchase busPurchase = busPurchaseService.getById(1L);
        Map<String, Object> busPurchaseDetailMap = Maps.newHashMap();
        busPurchaseDetailMap.put("purchaseId", busPurchase.getPurchaseId());
        List<BusPurchaseDetails> busPurchaseDetailsList = (List<BusPurchaseDetails>) busPurchaseDetailsService.listByMap(busPurchaseDetailMap);
        busPurchase.setDetails(busPurchaseDetailsList);
        Map<String, Object> busMaterialMap = Maps.newHashMap();
        busMaterialMap.put("materialPlanId", busPurchase.getPurchaseId());
        List<Long> plan100s = Lists.newArrayList();
        plan100s.add(1L);
        plan100s.add(2L);
        List<BusMaterialPlan100> busMaterialPlan100s = (List<BusMaterialPlan100>) busMaterialPlan100Service.listByIds(plan100s);
        // syncSrmService.materialRequest(busPurchase, busMaterialPlan100s, 100, "PMS测试");
//        syncSrmService.materialRequest(busPurchase, "PMS测试");

    }

    private void sendToOa() {
        String url = "http://192.168.0.67:88/services/UseridsWebService";
        //url = "http://218.21.240.106:8899/services/UseridsWebService";
        SoapClient client = SoapClient.create("url")
//             设置要请求的方法，此接口方法前缀为web，传入对应的命名空间
            .setMethod("test", "webservice.xuch.interfaces.weaver.com.cn")
            .setParam("tt", "218.21.240.106");

        // 发送请求，参数true表示返回一个格式化后的XML内容
        // 返回内容为XML字符串，可以配合XmlUtil解析这个响应
        String rs = client.send(true);
        System.out.println(rs);
//        Console.log(client.send(true));

    }

    // 开口订单
    private void materialRequestForOpen() {
        BusPurchase busPurchase = busPurchaseService.getById(1L);
        Map<String, Object> busPurchaseDetailMap = Maps.newHashMap();
        busPurchaseDetailMap.put("purchaseId", busPurchase.getPurchaseId());
        List<BusPurchaseDetails> busPurchaseDetailsList = (List<BusPurchaseDetails>) busPurchaseDetailsService.listByMap(busPurchaseDetailMap);
        busPurchase.setDetails(busPurchaseDetailsList);
//        Map<String, Object> busMaterialMap = Maps.newHashMap();
//        busMaterialMap.put("materialPlanId", busPurchase.getPurchaseId());
//        List<Long> plan100s = Lists.newArrayList();
//        plan100s.add(1L);
//        plan100s.add(2L);
//        List<BusMaterialPlan100> busMaterialPlan100s = (List<BusMaterialPlan100>) busMaterialPlan100Service.listByIds(plan100s);
//        syncSrmService.openOrderRequest(busPurchase);

    }

    public void calVal() {
//        BigDecimal rs = pmsApiUtill.getCalVal("master_cal_1", "主材费", BigDecimal.valueOf(1L), BigDecimal.valueOf(2L));
//        System.out.println(rs);
    }

    private void createContractFcb() {
        List<BusMaterialPackage100> package100s = busMaterialPackage100Service.list();
        BusProjectSupplier busSuppliers = busProjectSupplierService.list().get(0);
//        syncSrmService.planCreate(package100s, busSuppliers, 100, "PMS分包测试");
    }

    private void sync_materi(){
        String[] ids = {
            "M034401080131"
            ,"M034403040179"
            ,"M030301010018"
            ,"M030101010008"
            ,"M034602010205"
            ,"M022114030002"
            ,"M022101010010"
            ,"M022131020002"
            ,"M032502070008"
            ,"M032502020002"
            ,"M032504010003"
            ,"M032504021147"
            ,"M032501100015"
            ,"M015901010001"
            ,"M015901010002"
            ,"M015901010003"
            ,"M023801010014"
            ,"M034802010088"
            ,"M034802010085"
            ,"M034902010002"
            ,"M034902010003"
            ,"M024202010012"
            ,"M024307030002"
            ,"M025801010001"
            ,"M023901030009"
            ,"M023901010174"
            ,"M026101010003"
            ,"M026102010002"
            ,"M026103010003"
            ,"M026002010010"
            ,"M026003020001"
            ,"M050606010001"
            ,"M036601010004"
            ,"M036601010005"
            ,"M036502020012"
            ,"M036502010005"
            ,"M036501020019"
            ,"M036501020021"
            ,"M036507010014"
            ,"M036611010001"
            ,"M041701010001"
            ,"M030901020005"
            ,"M050133010007"
            ,"M035704010012"
            ,"M030106010001"
            ,"M036002010003"
            ,"M025901010001"
            ,"M041503010001"
            ,"M025902010006"
            ,"M030104020011"
            ,"M030104020005"
            ,"M025907040001"
            ,"M025914010002"
            ,"M030109010002"
            ,"M041904030001"
            ,"M041903010001"
            ,"M031001010037"
            ,"M023001010001"
            ,"M031001010036"
            ,"M033401010001"
        };
        Map<String, Object> params = Maps.newHashMap();
        params.put("ids", ids);
        synchroSrmToPmsService.sync_material(params);
    }

    public Boolean ckAppArovalStatus(Object reqData, String userNum, Long projectId, String majorCode, String appKind) {
//        if (ApiConstants.ENGINEER_APPROVAL_WZ_100_UPD.equals(appKind)
//            || ApiConstants.ENGINEER_APPROVAL_WZ_100_ADD.equals(appKind)
//            || ApiConstants.ENGINEER_APPROVAL_WZ_200_UPD.equals(appKind)
//            || ApiConstants.ENGINEER_APPROVAL_WZ_200_ADD.equals(appKind)) {
//            Map map = (Map)reqData;
//            List<Object> reqDataList = (List<Object>) map.get(ApiConstants.OA_APPROVAL_DATA);
//            reqDataList.stream().forEach(reqObj->{
//
//            });
//        }
        Map<String, Object> searchMap = Maps.newHashMap();
        searchMap.put("projectId", projectId);
        searchMap.put("majorCode", majorCode);
        searchMap.put("userNm", userNum);
        searchMap.put("appKind", appKind);
        searchMap.put("status", ApiConstants.APPROVAL_ING);

        Collection<BusOaApprovalSync> busOaApprovalSyncs = oaApprovalSyncService.listByMap(searchMap);
        if(0 < busOaApprovalSyncs.size()) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public String getMajorCodeByUserId(Long userId) {
        String majorCode = "";
        List<String> majorCodes = busMajorService.getUserMajors(userId);
        if (majorCodes.size() > 0) {
            if (!majorCodes.contains("P99")) {
                majorCode = majorCodes.get(0);
            }
        }
        return majorCode;
    }

    public void setbusOaApprovalSyncForBegin(BusOaApprovalSync busOaApprovalSync, Object reqData, String approvalUrl, String userNum, String appKind, String projectId) {
        Map map = (Map) reqData;
        List<String> majorCodes=busMajorService.getUserMajors(OpenHelper.getUserId());
        if(ApiConstants.ENGINEER_APPROVAL_WZ_100_UPD.equals(appKind)
            || ApiConstants.ENGINEER_APPROVAL_WZ_100_ADD.equals(appKind)) {

            Integer type = TypeUtils.castToInt(map.get("dataType"));
            CriteriaUpdate<BusMaterialPlan100> cu = new CriteriaUpdate<>();
            cu.eq("projectId", Long.valueOf(projectId));
            cu.eq("planType", type);
            cu.eq("versionStatus", 0);
            if (majorCodes.size() > 0) {
                if (!majorCodes.contains("P99")) {
                    cu.in("majorCode", majorCodes);
                }
            }
            cu.set("applayStatus", 1);
            List<BusMaterialPlan100> plan100s = busMaterialPlan100Service.list(cu);

        } else if(ApiConstants.ENGINEER_APPROVAL_WZ_200_UPD.equals(appKind)
            || ApiConstants.ENGINEER_APPROVAL_WZ_200_ADD.equals(appKind)) {
            // 物资审批
            Integer type = TypeUtils.castToInt(map.get("dataType"));
            CriteriaUpdate<BusMaterialPlan200> cu = new CriteriaUpdate<>();
            cu.eq("projectId", Long.valueOf(projectId));
            cu.eq("planType", type);
            cu.eq("versionStatus", 0);
            if (majorCodes.size() > 0) {
                if (!majorCodes.contains("P99")) {
                    cu.in("majorCode", majorCodes);
                }
            }
            cu.set("applayStatus", 1);
            List<BusMaterialPlan200> plan200s = busMaterialPlan200Service.list(cu);

        } else if(ApiConstants.ENGINEER_APPROVAL_FB_100_UPD.equals(appKind)
            || ApiConstants.ENGINEER_APPROVAL_FB_100_ADD.equals(appKind)
            || ApiConstants.ENGINEER_APPROVAL_FB_200_UPD.equals(appKind)
            || ApiConstants.ENGINEER_APPROVAL_FB_200_ADD.equals(appKind)) {
            // 分包审批

        }
    }

}
